<template>
    <el-container>
        <el-row :gutter="20" type="flex" justify="center" align="middle">
            <el-col :span="8">
                <el-card class="box-card" shadow="hover">
                    <el-form-item label="新增组别：">
                        <div class="custom-group-input-container">
                            <el-input v-if="eventForm.customGroupInputVisible" v-model="eventForm.customGroupInput"
                                @keyup.enter="submitFormCategory" placeholder="新组别" size="small">
                            </el-input>
                            <el-button v-else type="primary" size="small" @click="dialogVisible = true"
                                class="custom-button">
                                +新增组别
                            </el-button>
                        </div>
                        <div class="custom-group-tags-container">
                            <el-tag v-for="group in eventForm.groups" :key="group.groupname" closable
                                @close="removeGroup(group)" style="font-size: 15px;">
                                {{ group.groupname }}
                            </el-tag>
                        </div>
                    </el-form-item>
                </el-card>
            </el-col>
            <el-col :span="8">
                <el-card class="box-card" shadow="hover">
                    <el-form-item label="新增项目：">
                        <el-button type="primary" size="small" @click="dialogVisibleProject = true">
                            +新增项目
                        </el-button>
                    </el-form-item>
                </el-card>
            </el-col>
            <el-col :span="8">
                <el-card class="box-card" shadow="hover">
                    <el-form-item label="删除组别：">
                        <el-select v-model="eventForm.selectedGroup" placeholder="选择组别">
                            <el-option v-for="group in groups" :key="group.groupname" :label="group.groupname"
                                :value="group.id">
                            </el-option>
                        </el-select>
                        <el-button type="danger" size="small" @click="deleteGroup">
                            删除组别
                        </el-button>
                    </el-form-item>
                </el-card>
            </el-col>
        </el-row>
        <el-dialog title="添加组别：" v-model="dialogVisible" width="30%" @close="resetForm">
            <el-form :model="newGroup">
                <el-form-item label="组别名称" label-width="120px">
                    <el-input v-model="newGroup.groupname" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="参赛性别" label-width="120px">
                    <el-radio-group v-model="newGroup.sex">
                        <el-radio :value="1" size="large">男</el-radio>
                        <el-radio :value="0" size="large">女</el-radio>
                        <el-radio :value="2" size="large">不限</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="最大年龄" label-width="120px">
                    <el-input v-model="newGroup.maxAge" autocomplete="off" type="number"
                        @input="calculateBirthDates"></el-input>
                </el-form-item>
                <el-form-item label="最小年龄" label-width="120px">
                    <el-input v-model="newGroup.minAge" autocomplete="off" type="number"
                        @input="calculateBirthDates"></el-input>
                </el-form-item>
                <el-form-item label="最小出生日期" label-width="120px">
                    <el-date-picker v-model="newGroup.minBirthDay" type="date" placeholder="选择日期"
                        disabled></el-date-picker>
                </el-form-item>
                <el-form-item label="最大出生日期" label-width="120px">
                    <el-date-picker v-model="newGroup.maxBirthDay" type="date" placeholder="选择日期"
                        disabled></el-date-picker>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitNewGroup">提交</el-button>
            </template>
        </el-dialog>
        <el-dialog title="添加比赛项目" v-model="dialogVisibleProject" width="30%">
            <el-form :model="newProject">
                <el-form-item label="项目名称" label-width="120px">
                    <el-input v-model="newProject.projectName" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="项目队伍人数" label-width="120px">
                    <el-input v-model="newProject.projectPersonCount" autocomplete="off" type="number"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="dialogVisibleProject = false">取消</el-button>
                <el-button type="primary" @click="submitNewProject">提交</el-button>
            </template>
        </el-dialog>
    </el-container>
</template>

<script setup>
import { ref } from 'vue';
import { useRoute } from 'vue-router';
import axios from 'axios';
import { ElMessage } from 'element-plus';

const route = useRoute();

const matchId = route.query.matchId;

const token = localStorage.getItem('adminToken');


const eventForm = ref({
    customGroupInputVisible: false,
    customGroupInput: '',
    projectName: '',
    selectedGroup: null
});

const dialogVisible = ref(false);
const newGroup = ref({
    groupname: '',
    sex: null,
    maxAge: null,
    minAge: null,
    maxBirthDay: null,
    minBirthDay: null
});

const dialogVisibleProject = ref(false);
const newProject = ref({
    projectName: '',
    projectPersonCount: null
});

const groups = ref([]);
const submitFormCategory = () => {
    if (eventForm.value.customGroupInput) {
        eventForm.value.groups.push({ groupname: eventForm.value.customGroupInput });
        eventForm.value.customGroupInput = '';
        eventForm.value.customGroupInputVisible = false;
    }
};

//获取比赛组别(进行提前渲染)
async function fetchgrooups() {
    try {
        const respones = await axios.get(`http://back1.idcfengye.com:15173/competition/matchgroup/${matchId}`, {
            headers: {
                'Authorization': `Bearer ${token}`
            }
        });
        if (respones.data.msg) {
            groups.value = respones.data.matchgroup;
        }
    } catch (error) {
        console.log(error);

    }
}

fetchgrooups();


const submitFormProject = () => {
    // 添加项目的逻辑，这里打开添加项目的对话框
    dialogVisibleProject.value = true;
};

const removeGroup = (group) => {
    const index = eventForm.value.groups.indexOf(group);
    if (index !== -1) {
        eventForm.value.groups.splice(index, 1);
    }
};


//删除项目
// 删除项目
const deleteGroup = async () => {
    const matchGroupId = eventForm.value.selectedGroup;
    if (!matchGroupId) {
        ElMessage.error('请选择一个组别进行删除');
        return; // 如果没有选择组别，阻止进一步执行
    }
    try {
        const response = await axios.delete(`http://back1.idcfengye.com:15173/competition/matchgroup/delete/${matchGroupId}`, {
            headers: {
                'Authorization': `Bearer ${token}`
            }
        });
        // 检查响应数据中是否有消息
        if (response.data.success) {
            eventForm.value.selectedGroup = null;
            fetchGroups(); // 假设这是刷新组别列表的函数
            ElMessage.success('删除成功');
        } else if (response.data.msg) {
            // 根据后端返回的消息来判断错误类型
            if (response.data.msg.includes('有人填报该组别')) {
                ElMessage.error('该组别已有人填报，不可删除');
            } else {
                ElMessage.error(response.data.msg);
            }
        }
    } catch (error) {
        console.log(error.response.data);
        if (error.response && error.response.data) {
            // 根据后端返回的错误消息来提示用户
            if (error.response.data.msg) {
                ElMessage.error(error.response.data.msg);
            } else {
                ElMessage.error('删除操作失败，请稍后再试或联系管理员');
            }
        }
    }
};

//新增组别成功后清楚表单
const resetForm = () => {
    newGroup.value = {
        groupname: '',
        sex: null,
        maxAge: null,
        minAge: null,
        maxBirthDay: null,
        minBirthDay: null
    };
};

//新增组别
const submitNewGroup = async () => {
    if(newGroup.value.sex===''){
         ElMessage.error('性别要选择');
         return
    }
    if (!newGroup.value.groupname ||
        !newGroup.value.maxAge || !newGroup.value.minAge) {
        ElMessage.error('所有字段都是必填项，不可为空');
        return; // 退出函数，不进行提交
    }
    const newGroupData = {
        matchId: matchId,
        groupname: newGroup.value.groupname,
        sex: newGroup.value.sex,
        maxBirthDay: newGroup.value.maxBirthDay,
        minBirthDay: newGroup.value.minBirthDay,
    }
    try {
        const response = await axios.post(`http://back1.idcfengye.com:15173/competition/matchgroup/add`, newGroupData, {
            headers: {
                'Authorization': `Bearer ${token}`
            }
        })
        if (response.data.msg) {
            fetchgrooups();
            dialogVisible.value = false;
            resetForm();
            ElMessage.success('添加成功');
        }

    } catch (error) {
        console.log(error);

    }
};

//添加项目
const submitNewProject = async () => {
  // 验证项目名称和人数是否已填写
  if (!newProject.value.projectName || !newProject.value.projectPersonCount) {
    ElMessage.error('项目名称和项目队伍人数都是必填项，不可为空');
    return; // 如果有字段为空，阻止进一步执行
  }

  // 构建要发送的数据
  const newProjectData = {
    matchId: matchId, // 确保你有一个有效的matchId变量
    projectName: newProject.value.projectName,
    projectPersonCount: newProject.value.projectPersonCount
  };

  try {
    // 发送POST请求
    const response = await axios.post(`http://back1.idcfengye.com:15173/competition/project/add`, newProjectData, {
      headers: {
        "Content-Type": "application/json",
        "Authorization": `Bearer ${token}` // 确保headers中的字段是正确的
      }
    });

    // 检查响应消息
    if (response.data.success && response.data.msg) {
      dialogVisibleProject.value = false; // 关闭对话框
      resetProjectForm(); // 重置表单
      ElMessage.success(response.data.msg || '添加成功'); // 显示成功消息
    } else {
      // 如果后端返回的success为false，显示错误消息
      ElMessage.error(response.data.msg || '添加失败');
    }

  } catch (error) {
    console.error('添加项目失败:', error);
    ElMessage.error('添加项目失败，请检查网络或联系管理员'); // 显示错误消息
  }
};

const resetProjectForm = () => {
    newProject.value = {
        projectName: '',
        projectPersonCount: null
    };
};

// 计算出生日期
const calculateBirthDates = () => {
    const today = new Date();
    const minAge = parseInt(newGroup.value.minAge, 10) || 0;
    const maxAge = parseInt(newGroup.value.maxAge, 10) || 0;

    // 计算最小出生日期
    const minBirthDate = new Date(today.getFullYear() - minAge, today.getMonth(), today.getDate());
    newGroup.value.minBirthDay = minBirthDate.toISOString().split('T')[0];

    // 计算最大出生日期
    const maxBirthDate = new Date(today.getFullYear() - maxAge, today.getMonth(), today.getDate());
    newGroup.value.maxBirthDay = maxBirthDate.toISOString().split('T')[0];
};
</script>

<style scoped>
.el-container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 80vh;
}

.el-row {
    width: 100%;
}

.box-card {
    width: 100%;
    height: 500px;
    display: flex;
    flex-direction: column;
    justify-content: center;
}

.custom-group-input-container {
    display: flex;
    align-items: center;
}

.custom-button {
    margin-left: 8px;
}

.custom-group-tags-container {
    margin-top: 10px;
}
</style>